const express = require('express');
const { validate, configValidation } = require('../middleware/validate');
const configService = require('../services/config.service');
const { ApiError } = require('../utils/errorHandler');
const logger = require('../utils/logger');

const router = express.Router();

/**
 * @route   POST /api/configs
 * @desc    Create a new config
 * @access  Public
 */
router.post(
  '/',
  validate(configValidation.createConfig),
  async (req, res, next) => {
    try {
      const config = await configService.createConfig(req.body);
      logger.info(`Created new config with id: ${config.id}`);
      res.status(201).json({
        success: true,
        data: config,
      });
    } catch (error) {
      next(error);
    }
  },
);

/**
 * @route   GET /api/configs/:id
 * @desc    Get a config by id
 * @access  Public
 */
router.get(
  '/:id',
  validate(configValidation.getConfig),
  async (req, res, next) => {
    try {
      const config = await configService.getConfigById(req.params.id);
      res.status(200).json({
        success: true,
        data: config,
      });
    } catch (error) {
      next(error);
    }
  },
);

/**
 * @route   PUT /api/configs/:id
 * @desc    Update a config
 * @access  Public
 */
router.put(
  '/:id',
  validate(configValidation.updateConfig),
  async (req, res, next) => {
    try {
      const config = await configService.updateConfig(req.params.id, req.body);
      logger.info(`Updated config with id: ${config.id}`);
      res.status(200).json({
        success: true,
        data: config,
      });
    } catch (error) {
      next(error);
    }
  },
);

/**
 * @route   DELETE /api/configs/:id
 * @desc    Delete a config
 * @access  Public
 */
router.delete(
  '/:id',
  validate(configValidation.deleteConfig),
  async (req, res, next) => {
    try {
      await configService.deleteConfig(req.params.id);
      logger.info(`Deleted config with id: ${req.params.id}`);
      res.status(200).json({
        success: true,
        data: {},
        message: 'Configuration deleted successfully',
      });
    } catch (error) {
      next(error);
    }
  },
);

/**
 * @route   GET /api/configs
 * @desc    Get all configs with pagination
 * @access  Public
 */
router.get(
  '/',
  validate(configValidation.getConfigs),
  async (req, res, next) => {
    try {
      const result = await configService.getConfigs(req.query);
      res.status(200).json({
        success: true,
        data: result.configs,
        meta: {
          total: result.total,
          page: result.page,
          limit: result.limit,
          pages: Math.ceil(result.total / result.limit),
        },
      });
    } catch (error) {
      next(error);
    }
  },
);

/**
 * @route   GET /api/configs/search
 * @desc    Search configs by term
 * @access  Public
 */
router.get(
  '/search',
  validate(configValidation.searchConfigs),
  async (req, res, next) => {
    try {
      const { q, ...options } = req.query;
      const result = await configService.searchConfigs(q, options);
      res.status(200).json({
        success: true,
        data: result.configs,
        meta: {
          total: result.total,
          page: result.page,
          limit: result.limit,
          pages: Math.ceil(result.total / result.limit),
        },
      });
    } catch (error) {
      next(error);
    }
  },
);

module.exports = router;
